package com.travel.commons.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页工具类
 *
 * @author pengrui.r@qq.com
 */
@Data
public class PageUtils implements Serializable {
    /**
     * 页大小
     */
    private int pageSize;
    /**
     * 当前页
     */
    private int currPage;
    /**
     * 总页数
     */
    private int totalPage;
    /**
     * 总记录条数
     */
    private int totalCount;
    /**
     * 页数据列表
     */
    private List<?> regard;

    public PageUtils(IPage<?> page) {
        this.pageSize = (int) page.getSize();
        this.currPage = (int) page.getCurrent();
        this.totalPage = (int) page.getPages();
        this.totalCount = (int) page.getTotal();
        this.regard = page.getRecords();
    }

    public PageUtils(List<?> result, int totalCount, int pageSize, int currPage) {
        this.pageSize = pageSize;
        this.currPage = currPage;
        this.totalPage = (int) Math.ceil((double) totalCount / pageSize);
        this.totalCount = totalCount;
        this.regard = result;
    }

    /**
     * 数据分页
     * @param list 待分页的数据
     * @param limit 一页显示条数
     * @param currPage 当前页
     * @return 分页
     */
    public static PageUtils getPage(List<?> list, int limit, int currPage) {
        if (ObjectUtils.isEmpty(list) || list.size() == 0) {
            return new PageUtils(new ArrayList<>(), 0, limit, currPage);
        }
        int totalCount = list.size();
        int totalPage = 0;
        if (totalCount % limit == 0) {
            totalPage = totalCount / limit;
        } else {
            totalPage = totalCount / limit + 1;
        }

        if (totalPage < currPage) {
            currPage = totalPage;
        }

        int start = (currPage - 1) * limit;
        int end =  start + limit;
        if (currPage == totalPage) {// 当前页就是最后一页
            start = (currPage - 1) * limit;
            end = totalCount;
        }
        List<?> res = list.subList(start, end);
        return new PageUtils(res,totalCount,limit,currPage);
    }
}
